﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class AddProcessinfoHandler : IRequestHandler<AddProcessinfoCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<Processinfo> processRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddProcessinfoHandler> logger;

        public AddProcessinfoHandler(IProcessRepository<Processinfo> processRepository, IMapper mapper, ILogger<AddProcessinfoHandler> logger)
        {
            this.processRepository = processRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 工序新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AddProcessinfoCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model =mapper.Map<Processinfo>(request);
            model.CreateTime = DateTime.Now;
            model.Creater = "张三";

            var list =  processRepository.GetAllAsync().Where(x => x.ProcessCode == request.ProcessCode);
            if(list.Any())
            {
                result.Code=ErrorStatus.Error;
                result.Message = "工序编号重复,添加失败";
                
                return result;
            }
            var res  =processRepository.CreateAsync(model).Result;
            if(res>0)
            {
                result.Code=ErrorStatus.Success;
                result.Message = "添加工序成功";
                result.Data = res;
                return result;
            }
            else
            {
                result.Code = ErrorStatus.Error;
                result.Message = "添加工序失败";
                result.Data = res;
                return result;
            }
        }
    }
}
